package cn.idongjia.kuaidi.common;

import cn.idongjia.kuaidi.pojos.Track;
import cn.idongjia.kuaidi.pojos.TrackMessage;
import cn.idongjia.log.Log;
import cn.idongjia.log.LogFactory;
import com.alibaba.dubbo.common.utils.StringUtils;
import com.mongodb.Block;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import com.mongodb.client.model.Filters;

import javax.ws.rs.core.MultivaluedMap;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import static cn.idongjia.kuaidi.util.GsonUtil.GSON;

/**
 * Created by dongjia_lj on 16/4/11.
 */
public class MongoUtils {
    private static final Log LOGGER = LogFactory.getLog(MongoUtils.class);
    private static MongoCollection mongoCollection;
    private String mongoUrl;
    private String mongoDB;
    private String mongocoll;

    public void init() {
        MongoClientURI connectionString = new MongoClientURI(mongoUrl);
        MongoClient mongoClient = new MongoClient(connectionString);
        MongoDatabase mongoDatabase = mongoClient.getDatabase(mongoDB);
        mongoCollection = mongoDatabase.getCollection(mongocoll);

    }

    public static void add(String ooid, String outid, String companyname) {
        Document document = new Document("ooid", ooid).append("outid", outid).append("companyname",
                companyname).append
                ("tracklist", "");
        mongoCollection.insertOne(document);
    }

    public static TrackMessage findone(String ooid) {
        List<TrackMessage> results = find(ooid);
        if (null != results && results.size() > 0) {
            return results.get(0);
        }
        return null;
    }

    public static List<TrackMessage> find(String ooid) {

        FindIterable<Document> iterable = mongoCollection.find(Filters.eq("ooid", ooid));
        final List<TrackMessage> results = new ArrayList<TrackMessage>();
        iterable.forEach(new Block<Document>() {
            @Override
            public void apply(final Document document) {
                TrackMessage tm = new TrackMessage();
                tm.setOoid(document.getString("ooid"));
                tm.setOutid(document.getString("outid"));
                tm.setCompanyname(document.getString("companyname"));
                if (StringUtils.isNotEmpty(document.getString("tracklist"))) {
                    tm.setTrack(GSON.fromJson(document.getString("tracklist"), Track.class));
                }
                results.add(tm);
            }
        });

        return results;
    }

    public static void updateTrack(String outid, String tracklist) {
        Map params = new HashMap();
        params.put("outid", outid);
        params.put("tracklist", tracklist);
        mongoCollection.updateOne(new Document("outid",outid),new Document("$set",new Document
                ("tracklist",tracklist)));
    }

    public static void updateCompanyname(String ooid, String companyname) {
        Map params = new HashMap();
        params.put("ooid", ooid);
        params.put("companyname", companyname);
        update(params);
    }

    public static void update(Map params) {
        if (null != params) {
            Document document = new Document();
            Iterator iterator = params.entrySet().iterator();
            while (iterator.hasNext()) {
                Entry entry = (Entry) iterator.next();
                if (null != entry.getValue() && !"ooid".equals(entry.getKey())) {
                    document.append((String) entry.getKey(), entry.getValue());
                }
            }
            mongoCollection.updateOne(new Document("ooid", params.get("ooid")), new Document
                    ("$set", document));
        }
    }

    public static void delete(String ooid) {
        mongoCollection.deleteMany(new Document("ooid", ooid));
    }

    public String getMongoUrl() {
        return mongoUrl;
    }

    public void setMongoUrl(String mongoUrl) {
        this.mongoUrl = mongoUrl;
    }


    public String getMongoDB() {
        return mongoDB;
    }

    public String getMongocoll() {
        return mongocoll;
    }

    public void setMongocoll(String mongocoll) {
        this.mongocoll = mongocoll;
    }

    public void setMongoDB(String mongoDB) {
        this.mongoDB = mongoDB;
    }

    private static Document getTreeShip(MultivaluedMap<String, String> track) {

        Document document = new Document("outid", track.getFirst("outid"));
        document.append("companyname", track.getFirst("companyname"));
        document.append("tracklist", track.getFirst("tracklist"));
        return document;
    }
}
